<?php
/**
 * beimuaihui System
 * Copyright(c) 2011-2020 beimuaihui.
 * @license    http://www.gnu.org/licenses/gpl.html     This software Under GPL V3 License 
 * beimuaihui@gmail.com
 * http://code.google.com/p/beimuaihui/
 * $Id: ModelRelation.php 197 2011-02-18 12:45:33Z beimuaihui $
 */


Zend_Loader::loadClass("Baogg_Db_Table");

//class Permission extends Baogg_Db_Table {
class ModelRelation  extends Baogg_Db_Table {
	/**
	 * The default table name 
	 */
	protected $_name;
	protected $_db ;
	protected $_primary; 
	
	function __construct() {
		$this->_name =   'model_relation';
		
		$this->myPrimary= $this->_primary='model_relation_id';
		parent::__construct();
	}	
	

	
	function getSame($arr) {	
		$ret=array();
		
	    $sql = "SELECT {$this->myPrimary} FROM {$this->_name} WHERE model_id='{$arr['model_id']}' and  model_pid ='{$arr['model_pid']}' ";
		//var_dump($arr);var_dump($this->myPrimary); echo $sql;exit();
		$rs = $this->_db->query($sql)->fetchAll();
		foreach((array)$rs as $v)
		{
		    $ret[]=$v[$this->myPrimary];
		}
		return $ret; 	
	
	}
	
	/**
	 * 
	 * copy model_pid's table.column to model_id.fields
	 * @param unknown_type $model_relation_id
	 * @return boolean|Ambigous <boolean, unknown, Zend_Db_Statement_Interface, Zend_Db_Statement, PDOStatement>
	 */
	function initExtTable($model_relation_id){
    	global $LANG;
    	
    	
    	$flag=true;
    	//var_dump($model_relation_id);exit;
    	Zend_Loader::loadClass("ModelField");
    	$ModelField=new ModelField();  
    	$Model=new Model();
    	if(!$model_relation_id){
    		return false;
    	}
    	$rs_model_relation=$this->getOne($model_relation_id);
    	$rs_p_model=$Model->getOne($rs_model_relation[0]['model_pid']);    	
    	try{
    		$main_table=$this->_db->query("desc ".$this->db_prefix."{$rs_p_model[0]['table_name']}")->fetchAll();    		
    	}catch(Exception $e){
    		return true;
    	}
    	//echo '<pre>';print_r($main_table);exit;
    	Baogg_Language::loadFile($this->db_prefix.$rs_p_model[0]['table_name']);
    	foreach($main_table as $v){
    		if(!$rs_model_relation[0]['is_select'] && $v['Field']!=$rs_model_relation[0]['foreign_key']){
    			continue;
    		}
    		 //primary key must use in ext table
    		$field=array( 
				'model_id'=>$rs_model_relation[0]['model_id'], 
				'field_name'=>$v['Field'], 
				'show_name'=>BAOGG_LANGUAGE::get($v['Field']), 
				'field_type'=>$v['Type'], 
    			'field_view'=>'textfield',
				'field_options'=>'', 
				'tips'=>'', 
				'check_pattern'=>'', 
				'check_error'=>'', 
				'model_pid'=>($v['Key']=='PRI'?$rs_model_relation[0]['model_id']:$rs_model_relation[0]['model_pid']),  
				'is_basic'=>1, 
				'state'=>1, 
				'ordering'=>0,
    			'init_value'=>empty($v['Default'])?'':$v['Default'],
    			'field_null'=>empty($v['Null'])?'YES':$v['Null'],//$v['Null']
    			'field_key'=>empty($v['Key'])?'':'MUL',//$v['Key']
    			'field_extra'=>''//empty($v['Extra'])?'':$v['Extra']//$v['Extra'],
    			//'init_value'=>$v['Default'], 
	    		//'field_null'=>$v['Null'], 
	    		//'field_key'=>$v['Key'], 
	    		//'field_extra'=>'' 
    		);
    		
    		$rs_field_view=$ModelField->getList(array('model_id'=>$rs_model_relation[0]['model_pid'],'field_name'=>$v['Field']));
    		$field['field_view']=$rs_field_view?$rs_field_view[0]['field_view']:'textfield';
    		$field['field_options']=$rs_field_view?$rs_field_view[0]['field_options']:'';
    		
    		$existField=$ModelField->getList(array('model_id'=>$rs_model_relation[0]['model_id'],'model_pid'=>$rs_model_relation[0]['model_pid'],'field_name'=>$v['Field']));
    		if(!$existField){
    			$_flag=$ModelField->_insert($field);
    			$flag=$flag && $_flag;  
    		}
    		  		
    	}
    	$flag=$this->genExtTableFK($model_relation_id);
    	return $flag;
    }
    
    /**
     * 
     * init N:1's relations to model_id
     * @param int $model_relation_id
     * @return boolean
     */
    /*function initMultiExtTable($model_relation_id){
    	global $LANG;
    	
    	
    	$flag=true;
    	
    	Zend_Loader::loadClass("ModelField");
    	$ModelField=new ModelField();  
    	$Model=new Model();
    	
    	if(!$model_relation_id){
    		return false;
    	}
    	$rs_model_relation=$this->getOne($model_relation_id);
    	$rs_p_model=$Model->getOne($rs_model_relation[0]['model_pid']);        	
    	try{
    		$main_table=$this->_db->query("desc ".$this->db_prefix."{$rs_p_model[0]['table_name']}")->fetchAll();    		
    	}catch(Exception $e){
    		return false;
    	}
    	
    	Baogg_Language::loadFile($rs_p_model[0]['table_name']);
    	foreach($main_table as $v){
    		 if($v['Field']!=$rs_model_relation[0]['foreign_key']){
    		 	continue;
    		 }
    		
    		 $field=array( 
				'model_id'=>$rs_model_relation[0]['model_id'], 
				'field_name'=>$v['Field'], 
				'show_name'=>BAOGG_LANGUAGE::get($v['Field']), 
				'field_type'=>$v['Type'], 
				'field_options'=>'', 
				'tips'=>'', 
				'check_pattern'=>'', 
				'check_error'=>'', 
				'model_pid'=>$rs_model_relation[0]['model_id'],  
				'is_basic'=>1, 
				'state'=>1, 
				'ordering'=>0,
    		 	'init_value'=>is_null($v['Default'])?'':$v['Default'],
    		    'field_null'=>is_null($v['Null'])?'YES':$v['Null'],//$v['Null']
    		    'field_key'=>is_null($v['Key'])?'':$v['Key'],//$v['Key'],
    		    'field_extra'=>is_null($v['Extra'])?'':$v['Extra']//$v['Extra'],
    		);
    		
    		$existField=$ModelField->getList(array('model_id'=>$rs_model_relation[0]['model_id'],'field_name'=>$v['Field']));
    		//echo __FILE__.__LINE__.'<pre>';print_r($existField);print_r($field);exit;
    		if(!$existField){
    			$_flag=$ModelField->_insert($field);
    			$flag=$flag && $_flag;  
    		}
    		
    		  		
    	}
    	
    	
    	
    	return $flag;
    }*/
	
    public function genExtTableFK($model_relation_id){
    	$flag=true;    	
    	  	
    	
    	$rs_model_relation=$this->getOne($model_relation_id);    	
    	if(!$rs_model_relation ||!is_array($rs_model_relation)){
    		return true;
    	}    	
    	
    	$Model=new Model();
    	$rs_model=$Model->getOne($rs_model_relation[0]['model_id']);
    	try{    		
    		$ext_table=$this->_db->query("desc ".$this->db_prefix."{$rs_model[0]['table_name']}")->fetchAll();
    		
    	}catch(Exception $e){
    		return $flag;
    	}
    	$fk=$rs_model_relation[0]['foreign_key'];
    	
    	$sql='';
    	foreach((array)$ext_table as $v){
    		if($v['Field']==$fk){
    			//UNI
	    		if(!in_array($v['Key'],array('MUL','PRI','UNI'))){
	    			$unique=$rs_model_relation[0]['is_unique_fk']?' UNIQUE ':'';
	    			$sql="create {$unique} index index_".$this->db_prefix."{$rs_model[0]['table_name']}_{$v['Field']}_1 on ".$this->db_prefix."{$rs_model[0]['table_name']}({$v['Field']}) ";
	    		}else{
	    			return true;
	    		}
	    		break;
    		}else{
    			continue;
    		}
    	}

    	if(!$sql){
    		return $flag;
    	}
    	
    	try{
    		$flag=$this->_db->query($sql);
    	}catch(Exception $e){
    		$flag=false;
    		$arr_table_exist=null;
    	}
    	
    	return $flag;
    }
    
    
}
